<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use think\Db;
/**
 * 生成数据返回值
 */
function ZHTReturn($msg, $status = -1, $data = []){
  $rs = ['status'=>$status,'msg'=>$msg];
  if(!empty($data))$rs['data'] = $data;
  return $rs;
}
/**
 * 删除一维数组里的多个key
 */
function ZHTUnset(&$data,$keys){
  if($keys!='' && is_array($data)){
    $key = explode(',',$keys);
    foreach ($key as $v)unset($data[$v]);
  }
}
/**
 * 获取https设置情况
 */
function ZHTProtocol(){
	return request()->isSsl()?'https://':'http://';
}
/**
 * 获取当前网址
 */
function ZHTPageUrl(){
	$url = (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
	$url .= $_SERVER['HTTP_HOST'];
	$url .= isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : urlencode($_SERVER['PHP_SELF']) . '?' . urlencode($_SERVER['QUERY_STRING']);
	return $url;
}
/**
 * 获取系统配置数据
 */
function ZHTConfig(){
	$rs = cache('ZHT_CONF');
	if(!$rs){
		$rv = Db::name('config')->field('configCode,configVal')->select();
		$rs = [];
		foreach ($rv as $v){
			$rs[$v['configCode']] = $v['configVal'];
		}
		// //获取风格
    //     $styles = Db::name('styles')->where('isUse','=',1)->field('styleSys,stylePath,id')->select();
    //     if(!empty($styles)){
	  //       foreach ($styles as $key => $v) {
		//         $rs['wst'.$v['styleSys'].'Style'] = $v['stylePath'];
		//         $rs['wst'.$v['styleSys'].'StyleId'] = $v['id'];
	  //       }
    //     }
    //     //判断资源路径
    //     $rs['resourcePath'] = ($rs['ossService']!='')?ZHTProtocol().$rs['ossBucket'].'.'.$rs['ossBucketDomain']:str_replace('/index.php','',request()->root());
    //     $rs['resourceDomain'] = ($rs['ossService']!='')?ZHTProtocol().$rs['ossBucket'].'.'.$rs['ossBucketDomain']:str_replace('/index.php','',request()->root(true));
		//获取上传文件目录配置
		$data = Db::name('data')->where([['catId','=',1],['dataFlag','=',1]])->column('dataVal');
		foreach ($data as $key => $v){
			$data[$key] = str_replace('_','',$v);
		}
		$rs['zhtUploads'] = $data;
		// if($rs['mallLicense']=='')$rs['mallSlogan'] = $rs['mallSlogan']."  ".base64_decode('UG93ZXJlZCBCeSBXU1RNYXJ0');
		// // 是否有app端
		// $prefix = config('database.prefix');
		// $rs['hasApp'] = !!Db::query("show tables like '{$prefix}app_session';");
		cache('ZHT_CONF',$rs,31536000);
	}
	return $rs;
}

/**
 * 获取指定的全局配置
 */
function ZHTConf($key,$v = ''){
	if(is_null($v)){
		if(array_key_exists('ZHTCONF',$GLOBALS) && array_key_exists($key,$GLOBALS['ZHTCONF'])){
		    unset($GLOBALS['ZHTCONF'][$key]);
		}
	}else if($v === ''){
		if(array_key_exists('ZHTCONF',$GLOBALS)){
			$conf = $GLOBALS['ZHTCONF'];
			$ks = explode(".",$key);
			for($i=0,$k=count($ks);$i<$k;$i++){
				if(array_key_exists($ks[$i],$conf)){
					$conf = $conf[$ks[$i]];
				}else{
					return null;
				}
			}
			return $conf;
		}
	}else{
		return $GLOBALS['ZHTCONF'][$key] = $v;
	}
	return null;
}
/**
* 资源管理
* @param $resourcePath    资源路径
* @param $fromType   0：用户/商家 1：平台管理员
* @param $resourceType   0：图片 1：视频 2：其他文件类型
*/
function ZHTRecordResource($resourcePath, $fromType, $resourceType=0){
	$data = [];
	$data['resourcePath'] = $resourcePath;
	if(file_exists($resourcePath)){
		$data['resourceSize'] = filesize($resourcePath); //返回字节数 resourceSize/1024 k  	resourceSize/1024/1024 m
	}
	//获取表名
	$table = explode('/',$resourcePath);
	$data['fromTable'] = $table[1];
	$data['fromType'] = (int)$fromType;
	//根据类型判断所有者
	$data['ownId'] = ((int)$fromType==0)?(int)session('ZHT_USER.userId'):(int)session('ZHT_STAFF.staffId');
	$data['resourceType'] = $resourceType;
	$data['create_time'] = time();

	//保存记录
	Db::name('resource')->insert($data);
}
/**
* 启用资源文件
* @param $fromType 0：  用户/商家 1：平台管理员
* @param $dataId        来源记录id
* @param $resourcePath       资源路径,要处理多个资源时请传入一位数组,或用","连接资源路径
* @param $fromTable     该记录来自哪张表
* @param $resFieldName  表中的资源字段名称
*/
function ZHTUseResource($fromType, $dataId, $resourcePath, $fromTable='', $resFieldName=''){
	// if(empty($resourcePath))return;
	if(empty($resourcePath) and $resFieldName == '')return;
	$image['dataId'] = (int)$dataId;
	$image['isUse'] = 1; //标记为启用
	if ($fromTable != '') {
		$tmp = ['', ''];
		if (strpos($fromTable, '-') !== false) {
			$tmp = explode('-', $fromTable);
			$fromTable = str_replace('-' . $tmp[1], '', $fromTable);
		}
		$image['fromTable'] = str_replace('_', '', $fromTable . $tmp[1]);
	}
	$resourcePath = is_array($resourcePath) ? $resourcePath : explode(',', $resourcePath);//转数组

	//用于与旧资源比较
	$newRes = $resourcePath;

	// 不为空说明执行修改
	if ($resFieldName != '') {
		//要操作的表名  $fromTable;
		// 获取`$fromTable`表的主键
		$tableName = $fromTable;
		$pk = Db::name("$tableName")->getPk();
		// 取出旧图
		// $oldresourcePath = model("$fromTable")->where("$pk", $dataId)->value("$resFieldName"); // 原来是这个，但是如果没有对应Model的话，就会出错，shop里面修改商品就碰到了
		$oldresourcePath = Db::name("$fromTable")->where("$pk", $dataId)->value("$resFieldName");
		// 转数组
		$oldresourcePath = explode(',', $oldresourcePath);

		// 1.要设置为启用的文件
		$newRes = array_diff($resourcePath, $oldresourcePath);
		// 2.要标记为删除的文件
		$oldresourcePath = array_diff($oldresourcePath, $resourcePath);
		//旧资源数组跟新资源数组相同则不需要继续执行
		if ($newRes != $oldresourcePath) ZHTUnuseResource($oldresourcePath);
	}
	if(!empty($newRes)){
		Db::name('resource')->where([['resourcePath','in',$newRes]])->update($image);
	}
}
/**
 * 标记无效资源文件
 * $fromTable 哪个表（common.php使用时，$fromTable直接赋予的图片路径，Model中使用时，$fromTable是数据表的名称，然后查询出图片路径）
 * $field 哪个字段
 * $dataId 哪个id,一个或多个（批量删除会有多个）
 * $isContent标记$field字段是不是编辑器字段
 */
function ZHTUnuseResource($fromTable, $field = '', $ids = '', $isContent = ''){
	if ($fromTable == '') return;
	$resourcePath = $fromTable;
	if ($field != '') {
		$ids = explode(',', $ids);
		$tableName = $fromTable;
		$pk = Db::name("$tableName")->getPk();
		// 取出旧资源
		$resourcePath = Db::name("$fromTable")->where([["$pk",'in',$ids]])->field("$field")->select();		
		if($isContent != ''){
			$oldImgPath = array();
			foreach($resourcePath as $vo){
				$oldDesc = htmlspecialchars_decode($vo["$field"]);
				$rule = '/src=".*?\/(upload.*?)"/';
				preg_match_all($rule,$oldDesc,$images);	
				$oldImgPath = array_merge($oldImgPath, $images[1]);
			}
			$resourcePath = $oldImgPath;
		}else{
      // $resourcePath = array_column($resourcePath, "$field"); // 单张上传图片用这个，但是因为涉及多图上传，字段值为多张图片，所以不适用了。
      $str = '';
      foreach($resourcePath as $vo){
        $str .= ',' . $vo["$field"];
      }
      $resourcePath = ltrim($str, ",");
		}		
	}
	if (!empty($resourcePath)) {
		$resourcePath = is_array($resourcePath) ? $resourcePath : explode(',', $resourcePath); //转数组
		Db::name('resource')->where([['resourcePath', 'in', $resourcePath]])->setField('isUse', 0);
	}
}
/**
* 编辑器图片标记为启用或删除
* @param $fromType 0：  用户/商家 1：平台管理员
* @param $dataId        来源记录id
* @param $oldDesc       旧商品描述
* @param $newDesc       新商品描述
*/
function ZHTEditorImageRocord($fromType, $dataId, $oldDesc, $newDesc){
	// 解义
	$oldDesc = htmlspecialchars_decode($oldDesc);
	$newDesc = htmlspecialchars_decode($newDesc);
	//编辑器里的图片
	$rule = '/src=".*?\/(upload.*?)"/';	
	// 获取旧的src数组
	preg_match_all($rule,$oldDesc,$images);	
	$oldImgPath = $images[1];
	// 获取新的src数组
	preg_match_all($rule,$newDesc,$images);		
	$imgPath = $images[1];
	
	// 1.要设置为启用的文件
	$newImage = array_diff($imgPath, $oldImgPath);
	
	// 2.要标记为删除的文件
	$oldImgPath = array_diff($oldImgPath, $imgPath);

	//旧图数组跟新图数组相同则不需要继续执行
	if($newImage!=$oldImgPath){
		//标记新图启用
		ZHTUseResource($fromType, $dataId, $newImage);
		//标记旧图删除
		ZHTUnuseResource($oldImgPath);
	}
}
/**
 * 获取系统根目录
 */
function ZHTRootPath(){
	return dirname(dirname(__File__));
}
/**
 * 切换图片
 * @param $imgurl 图片路径
 * @param $imgType 图片类型    0:PC版大图   1:PC版缩略图       2:移动版大图    3:移动版缩略图
 * @param $default 图片默认    mallLogo:商城Logo goodsLogo:商品默认 shopLogo:店铺默认 userLogo:会员默认
 * 图片规则
 * PC版版大图 :201635459344.jpg
 * PC版版缩略图 :201635459344_thumb.jpg
 * 移动版大图 :201635459344_m.jpg
 * 移动版缩略图 :201635459344_m_thumb.jpg
 */
function ZHTImg($imgurl,$imgType = 1,$default = ''){
	// $m = ZHTConf('CONF.wstMobileImgSuffix');
	$m = 'm';
	$imgurl = str_replace($m.'.','.',$imgurl);
	$imgurl = str_replace($m.'_thumb.','.',$imgurl);
	$imgurl = str_replace('_thumb.','.',$imgurl);
	$img = '';
	switch ($imgType){
		case 0:$img =  $imgurl;break;
		case 1:$img =  str_replace('.','_thumb.',$imgurl);break;
		case 2:$img =  str_replace('.',$m.'.',$imgurl);break;
		case 3:$img =  str_replace('.',$m.'_thumb.',$imgurl);break;
	}
	$img = ((file_exists(ZHTRootPath()."/public/".$img))?$img:$imgurl);
    // if(ZHTConf('CONF.ossService')==""){
    //     $img = ((file_exists(ZHTRootPath()."/".$img))?$img:$imgurl);
    //     if($default){
    //         $img = ((file_exists(ZHTRootPath()."/".$img) && $img)?$img:ZHTConf('CONF.'.$default));
    //     }
    // }

	return $img;
}
/**
 * 图片为空，用默认图片代替
 */
function ZHTImgEmpty($imgurl){
	if($imgurl == '')return 'static/images/nopic.gif';
	return $imgurl;
}
/**
 * 补充图片路径
 * @param $imgurl 图片路径，判断图片路径是否包含http，如果包含，原样返回，如果不包含，加/返回
 */
function ZHTImgUrl($imgurl){
	if ($imgurl == '' || strpos($imgurl, 'http') !== false) {
		return $imgurl;
	}else{
		return '/' . $imgurl;
	}
}
/**
 * 图片路径加域名
 * @param $imgurl 图片路径，判断图片路径是否包含http，如果包含，原样返回，如果不包含，加/返回
 */
function ZHTImgDomainUrl($imgurl){
	if($imgurl == '')return '';
	$domain = (substr(ZHTConf('CONF.webUrl'),-1) == '/') ? ZHTConf('CONF.webUrl') : ZHTConf('CONF.webUrl') . '/';
	return str_replace('upload',$domain.'upload',$imgurl);
}
/**
 * 内容图片路径加域名
 * @param $content 图片路径，判断图片路径是否包含http，如果包含，原样返回，如果不包含，加/返回
 */
function ZHTContentDomainUrl($content){
	if($content == '')return '';
	$domain = (substr(ZHTConf('CONF.webUrl'),-1) == '/') ? ZHTConf('CONF.webUrl') : ZHTConf('CONF.webUrl') . '/';
	return str_replace('src="/upload','src="'.$domain.'upload',$content);
}
/**
 * 检测图片是否需要旋转
 */
function checkImageOrientation($image, $imageSrc){
	if(!is_file($imageSrc))return $image;
	try{
		$exif = exif_read_data($imageSrc);
		if(isset($exif['Orientation']) && !empty($exif['Orientation'])) {
			switch($exif['Orientation']) {
				// 插件中对传入的角度前面加上的负数(-)，故传入角度时需与文档中取反
				// 文档参考：https://www.php.net/manual/zh/function.exif-read-data.php 关键字：Orientation
				case 8:
					$image = $image->rotate(-90);
				break;
				case 3:
					$image = $image->rotate(-180);
				break;
				case 6:
					$image = $image->rotate(90);
				break;
			}
		}
		$image->save($imageSrc, $image->type(), 100);
		return $image;
	}catch(\Exception $e){
		return $image;
	}
}
/**
 * 上传图片
 * 需要生成缩略图： isThumb=1
 * 需要加水印：isWatermark=1
 * pc版缩略图： width height
 * 手机版原图：mWidth mHeight
 * 缩略图：mTWidth mTHeight
 * 判断图片来源：fromType 0：商家/用户   1：平台管理员
 */
function ZHTUploadPic($fromType = 0){	
	$fileKey = key($_FILES);
	$dir = input('param.dir');
	if($dir == '')return json_encode(['msg'=>'没有指定文件目录！','status'=>-1]);	
	$dirs = ZHTConf('CONF.zhtUploads');
	if(!in_array($dir,$dirs)){
		return json_encode(['msg'=>'非法文件目录！','status'=>-1]);
	}
	// 上传文件
	$file = request()->file($fileKey);
	if($file===null){
		return json_encode(['msg'=>'上传文件不存在或超过服务器限制','status'=>-1]);
	}
	$rule = [
		'type'=>'image/png,image/gif,image/jpeg,image/x-ms-bmp',
		'ext'=>'jpg,jpeg,gif,png,bmp',
		'size'=>'20971520'
	];
		
	$info = $file->validate($rule)->rule('uniqid')->move(Env::get('root_path').'public/upload/'.$dir."/".date('Y-m'));
	
	if($info){
		$imageSrc = $info->getPathname();
		// return json_encode(['msg'=>$imageSrc,'status'=>-1]);
		$filePath = str_replace(Env::get('root_path').'public/','',$imageSrc);
		$filePath = str_replace('\\','/',$filePath);
		$imgSrc = $info->getFilename();
		$savePath = str_replace($imgSrc,'',$filePath);
	// 	return json_encode(['msg'=>$imageSrc,'status'=>-1]);	
	// die;
		//原图路径
		// $imageSrc = trim($filePath.$imgSrc,'/'); // 没用，废弃
		//图片记录
		ZHTRecordResource($filePath, (int)$fromType);
		//打开原图
		$image = \image\Image::open($imageSrc);
		//缩略图路径 手机版原图路径 手机版缩略图路径
		$thumbSrc = $mSrc = $mThumb = null;
		//手机版原图宽高
		$mWidth = min($image->width(),(int)input('mWidth',700));
		$mHeight = min($image->height(),(int)input('mHeight',700));
		//手机版缩略图宽高
		$mTWidth = min($image->width(),(int)input('mTWidth',250));
		$mTHeight = min($image->height(),(int)input('mTHeight',250));
		
		/****************************** 生成缩略图 *********************************/
		$isThumb = (int)input('isThumb');
		if($isThumb==1){
			// 检测是否需要翻转图片-不知道什么作用
			$image = checkImageOrientation($image, $imageSrc);
			//缩略图路径
			$thumbSrc = ZHTStrReplaceLast('.', '_thumb.', $imageSrc);
			// 缩略图自动补白
			// $image->thumb((int)input('width',min(300,$image->width())), (int)input('height',min(300,$image->height())),2)->save($thumbSrc,$image->type(),90);
			// 缩略图保持原比例
			$image->thumb((int)input('width',min(300,$image->width())), (int)input('height',min(300,$image->height())))->save($thumbSrc,$image->type(),90);
			//是否需要生成移动版的缩略图
			if(ZHTConf("CONF.isMobileImg") == 1){
				$suffix = '_m';
				$image = \image\Image::open($imageSrc);
				$mSrc = ZHTStrReplaceLast('.',"$suffix.",$imageSrc);
				$mThumb = ZHTStrReplaceLast('.', '_thumb.',$mSrc);
				$image->thumb($mWidth, $mHeight)->save($mSrc,$image->type(),90);
				$image->thumb($mTWidth, $mTHeight)->save($mThumb,$image->type(),90);
			}
		}

		/***************************** 添加水印 ***********************************/
		$isWatermark = (int)input('isWatermark');
		if ($isWatermark == 1 && (int)ZHTConf('CONF.watermarkPosition') !== 0) {
			//取出水印配置
			$wmWord = ZHTConf('CONF.watermarkWord'); //文字
			$wmFile = trim(ZHTConf('CONF.watermarkFile'), '/'); //水印文件
			//判断水印文件是否存在
			if (!file_exists(ZHTRootPath() . "/public/" . $wmFile)) $wmFile = '';
			$wmPosition = (int)ZHTConf('CONF.watermarkPosition'); //水印位置
			$wmSize = ((int)ZHTConf('CONF.watermarkSize') != 0) ? ZHTConf('CONF.watermarkSize') : '20'; //大小
			$wmColor = (ZHTConf('CONF.watermarkColor') != '') ? ZHTConf('CONF.watermarkColor') : '#000000'; //颜色必须是16进制的
			$wmOpacity = ((int)ZHTConf('CONF.watermarkOpacity') != 0) ? ZHTConf('CONF.watermarkOpacity') : '100'; //水印透明度
			//是否有自定义字体文件
			$customTtf = Env::get('root_path') . ZHTConf('CONF.watermarkTtf');
			$ttf = is_file($customTtf) ? $customTtf : Env::get('extend_path') . 'verify/verify/zhttfs/1.ttf';
			$image = \image\Image::open($imageSrc);
			if (!empty($wmWord)) { //当设置了文字水印 就一定会执行文字水印,不管是否设置了文件水印
				// 文字偏移量
				$offset = ZHTConf('CONF.watermarkOffset');
				if ($offset != '') {
					$offset = explode(',', str_replace('，', ',', $offset));
					$offset = array_slice($offset, 0, 2);
					$offset = array_map(function ($val) {
						return (int)$val;
					}, $offset);
					if (count($offset) < 2) array_push($offset, 0);
				}
				//执行文字水印
				$image->text($wmWord, $ttf, $wmSize, $wmColor, $wmPosition, $offset)->save($imageSrc);
				if ($thumbSrc !== null) { // 本来缩略图和手机图片已经存在了，为什么还要重新生成缩略图？如果缩略图添加水印，需要打开$thumbSrc，$image2 = \image\Image::open($thumbSrc)然后保存，是打开原图$imageSrc重新生成缩略图，还是打开缩略图加水印，自己选择
					$image->thumb((int)input('width', min(300, $image->width())), (int)input('height', min(300, $image->height())))->save($thumbSrc, $image->type(), 90);
				}
				//如果有生成手机版原图
				if (!empty($mSrc)) {
					$image = \image\Image::open($imageSrc);// 不知道为什么需要重新open一下，直接用$image不行
					$image->thumb($mWidth, $mHeight)->save($mSrc, $image->type(), 90);
					$image->thumb($mTWidth, $mTHeight)->save($mThumb, $image->type(), 90);
				}
			} elseif (!empty($wmFile)) { //设置了文件水印,并且没有设置文字水印
				//执行图片水印
				$image->water($wmFile, $wmPosition, $wmOpacity)->save($imageSrc);
				if ($thumbSrc !== null) {
					$image->thumb((int)input('width', min(300, $image->width())), (int)input('height', min(300, $image->height())))->save($thumbSrc, $image->type(), 90);
				}
				//如果有生成手机版原图
				if ($mSrc !== null) {
					$image = \image\Image::open($imageSrc); // 不知道为什么需要重新open一下，直接用$image不行
					$image->thumb($mWidth, $mHeight)->save($mSrc, $image->type(), 90);
					$image->thumb($mTWidth, $mTHeight)->save($mThumb, $image->type(), 90);
				}
			}
		}

		//判断是否有生成缩略图
		$thumbSrc = ($thumbSrc==null)?$info->getFilename():ZHTStrReplaceLast('.','_thumb.', $info->getFilename());
		$savePath = ltrim($savePath,'/');
		$info = null;
		$rdata = ['status'=>1,'savePath'=>$savePath,'name'=>$imgSrc,'thumb'=>$thumbSrc];
    return json_encode($rdata);
	}else{
		//上传失败获取错误信息
		return $file->getError();
	}
}
/**
* 替换符合条件的最后一个字符串
*/
function ZHTStrReplaceLast($search, $replace, $subject){
  $pos = strrpos($subject, $search);
	if($pos !== false){
    $subject = substr_replace($subject, $replace, $pos, strlen($search));
  }
	return $subject;
}
/**
* 编辑器上传图片
* {"code":"000","message":"上传成功.","count":null,"page":null,"pagesize":null,"extra":null,"data":{"url":"upload/erdfderert043.png"}}
*/
function ZHTEditorUpload($fromType = 0){
	//PHP上传失败
	if (!empty($_FILES['imgFile']['error'])) {
		switch ($_FILES['imgFile']['error']) {
			case '1':
				$error = '超过php.ini允许的大小。';
				break;
			case '2':
				$error = '超过表单允许的大小。';
				break;
			case '3':
				$error = '图片只有部分被上传。';
				break;
			case '4':
				$error = '请选择图片。';
				break;
			case '6':
				$error = '找不到临时目录。';
				break;
			case '7':
				$error = '写文件到硬盘出错。';
				break;
			case '8':
				$error = 'File upload stopped by extension。';
				break;
			case '999':
			default:
				$error = '未知错误。';
		}
		return ['code' => "001", 'message' => $error];
	}

  $fileKey = key($_FILES);
	$dir = 'image'; // 编辑器上传图片目录
	$dirs = ZHTConf('CONF.zhtUploads');
	if(!in_array($dir,$dirs)){
		return json_encode(['code'=>"001",'message'=>'非法文件目录！']);
	}
	// 上传文件
	$file = request()->file($fileKey);
	if($file===null){
		return json_encode(["code"=>"001","message"=>'上传文件不存在或超过服务器限制']);
	}
	$rule = [
		'type'=>'image/png,image/gif,image/jpeg,image/x-ms-bmp',
		'ext'=>'jpg,jpeg,gif,png,bmp',
		'size'=>'20971520'
	];
	$mediaType = 0;
	if(input('dir')=='media'){
		// 上传类型为视频或音频时，不限制大小
		$rule = array_diff_key($rule, ['size'=>'']);
		$videoExt = "3gp,mp4,rmvb,mov,avi,m4v";
		$rule['ext'] .= $videoExt;
		$typeArr = explode(',', $videoExt);
		foreach($typeArr as $v){
			$rule['type'] .= ",video/$v";
		}
		// 上传的资源类型为视频
		$mediaType = 1;
	}
	$info = $file->validate($rule)->rule('uniqid')->move(Env::get('root_path').'public/upload/'.$dir."/".date('Y-m'));
	
	if ($info) {
		$imageSrc = $info->getPathname();
		$filePath = str_replace(Env::get('root_path').'public/','',$imageSrc);
		$filePath = str_replace('\\','/',$filePath);
		// $imgSrc = $info->getFilename();
		// $savePath = str_replace($imgSrc,'',$filePath);

		$extension = $info->getExtension();
		if (in_array($extension, ['jpg', 'jpeg', 'gif', 'png', 'bmp'])) {
			//原图路径
			// $imageSrc = trim($filePath . $name, '/');
			//打开原图
			$image = \image\Image::open($imageSrc);

			//手机版原图宽高
			$mWidth = min($image->width(), (int)input('mWidth', 700));
			$mHeight = min($image->height(), ((int)input('mHeight', 700) > $image->height()) ? $image->height() : $image->height() / 2);
			/****************************** 生成移动大图 *********************************/

			//是否需要生成移动版的大图
			if(ZHTConf("CONF.isMobileImg") == 1){
				$suffix = '_m';
				$image = \image\Image::open($imageSrc);
				$mSrc = str_replace('.', "$suffix.", $imageSrc);
				$image->thumb($mWidth, $mHeight)->save($mSrc, $image->type(), 90);
			}

			/***************************** 添加水印 ***********************************/
			if ((int)ZHTConf('CONF.watermarkPosition') !== 0) {
				//取出水印配置
				$wmWord = ZHTConf('CONF.watermarkWord'); //文字
				$wmFile = trim(ZHTConf('CONF.watermarkFile'), '/'); //水印文件
				//判断水印文件是否存在
				if (!file_exists(ZHTRootPath() . "/public/" . $wmFile)) $wmFile = '';
				$wmPosition = (int)ZHTConf('CONF.watermarkPosition'); //水印位置
				$wmSize = ((int)ZHTConf('CONF.watermarkSize') != 0) ? ZHTConf('CONF.watermarkSize') : '20'; //大小
				$wmColor = (ZHTConf('CONF.watermarkColor') != '') ? ZHTConf('CONF.watermarkColor') : '#000000'; //颜色必须是16进制的
				$wmOpacity = ((int)ZHTConf('CONF.watermarkOpacity') != 0) ? ZHTConf('CONF.watermarkOpacity') : '100'; //水印透明度
				//是否有自定义字体文件
				$customTtf = Env::get('root_path') . ZHTConf('CONF.watermarkTtf');
				$ttf = is_file($customTtf) ? $customTtf : Env::get('extend_path') . 'verify/verify/zhttfs/1.ttf';
				$image = \image\Image::open($imageSrc);
				if (!empty($wmWord)) { //当设置了文字水印 就一定会执行文字水印,不管是否设置了文件水印
					// 文字偏移量
					$offset = ZHTConf('CONF.watermarkOffset');
					if ($offset != '') {
						$offset = explode(',', str_replace('，', ',', $offset));
						$offset = array_slice($offset, 0, 2);
						$offset = array_map(function ($val) {
							return (int)$val;
						}, $offset);
						if (count($offset) < 2) array_push($offset, 0);
					}
					//执行文字水印
					$image->text($wmWord, $ttf, $wmSize, $wmColor, $wmPosition, $offset)->save($imageSrc);

					//如果有生成手机版原图
					if (!empty($mSrc)) {
						$image = \image\Image::open($imageSrc);
						$image->thumb($mWidth, $mHeight)->save($mSrc, $image->type(), 90);
					}
				} elseif (!empty($wmFile)) { //设置了文件水印,并且没有设置文字水印
					//执行图片水印
					$image->water($wmFile, $wmPosition, $wmOpacity)->save($imageSrc);
					//如果有生成手机版原图
					if ($mSrc !== null) {
						$image = \image\Image::open($imageSrc);
						$image->thumb($mWidth, $mHeight)->save($mSrc, $image->type(), 90);
					}
				}
			}
		}

		$info = null;
		//图片记录
		ZHTRecordResource($filePath, (int)$fromType, $mediaType);
		// ZHTRecordResources($imageSrc, (int)$fromType, $mediaType);
		return json_encode(["code" => "000", "message" => "", 'data' => ['url' => '/'.$filePath]]);
	}
	return json_encode(["code"=>"001","message"=>$file->getError()]);
}
/**
 * 上传视频
 * 判断图片来源：fromType 0：商家/用户   1：平台管理员
 */
function ZHTUploadVideo($fromType = 0){	
	$fileKey = key($_FILES);
	$dir = input('param.dir');
	if($dir == '')return json_encode(['msg'=>'没有指定文件目录！','status'=>-1]);	
	$dirs = ZHTConf('CONF.zhtUploads');
	if(!in_array($dir,$dirs)){
		return json_encode(['msg'=>'非法文件目录！','status'=>-1]);
	}
	// 上传文件
	$file = request()->file($fileKey);
	if($file===null){
		return json_encode(['msg'=>'上传文件不存在或超过服务器限制','status'=>-1]);
	}
	$rule = [
		'ext'=>'3gp,mp4,rmvb,mov,avi,m4v'
	];
		
	$info = $file->validate($rule)->rule('uniqid')->move(Env::get('root_path').'public/upload/'.$dir."/".date('Y-m'));
	
	if($info){
		$imageSrc = $info->getPathname();
		$filePath = str_replace(Env::get('root_path').'public/','',$imageSrc);
		$filePath = str_replace('\\','/',$filePath);
		$imgSrc = $info->getFilename();
		$savePath = str_replace($imgSrc,'',$filePath);
		
		//视频记录
		ZHTRecordResource($filePath, (int)$fromType, 1);

		$savePath = ltrim($savePath,'/');
		$info = null;
		$rdata = ['status'=>1,'savePath'=>$savePath,'name'=>$imgSrc];
    return json_encode($rdata);
	}else{
		//上传失败获取错误信息
		return $file->getError();
	}
}
/**
 * 上传文件
 * 判断图片来源：fromType 0：商家/用户   1：平台管理员
 */
function ZHTUploadFile($fromType = 0){
	$fileKey = key($_FILES);
	$dir = input('param.dir');
	if($dir == '')return json_encode(['msg'=>'没有指定文件目录！','status'=>-1]);	
	
	// 上传文件
	$file = request()->file($fileKey);
	if($file===null){
		return json_encode(['msg'=>'上传文件不存在或超过服务器限制','status'=>-1]);
	}
	$rule = [
		'ext'=>'jpg,jpeg,gif,png,mp4,mov'
		// 'ext'=>'doc,docx,ppt,pptx,xls,xlsx,zip,pdf'
	];
		
	// $info = $file->validate($rule)->rule('uniqid')->move(Env::get('root_path').'upload/'.$dir."/".date('Y-m'));
	$info = $file->validate($rule)->rule('uniqid')->move($dir);
	
	if($info){
		$imageSrc = $info->getPathname();
		$filePath = str_replace(Env::get('root_path'),'',$imageSrc);
		$filePath = str_replace('\\','/',$filePath);
		$imgSrc = $info->getFilename();
		$savePath = str_replace($imgSrc,'',$filePath);

		$ext = pathinfo($filePath); // 获取文件后缀
		if(in_array($ext['extension'],['jpg','jpeg','gif','png'])){
			// 打开原图
			$image = \image\Image::open($imageSrc);
			// 检测是否需要翻转图片-不知道什么作用
			$image = checkImageOrientation($image, $imageSrc);
			//缩略图路径
			$thumbSrc = ZHTStrReplaceLast('.', '_thumb.', $imageSrc);
			// 缩略图保持原比例
			$image->thumb((int)input('width',min(1000,$image->width())), (int)input('height',min(1000,$image->height())))->save($thumbSrc,$image->type(),90);
			$imgSrc = ZHTStrReplaceLast('.', '_thumb.', $imgSrc);
		}
		
		//视频记录
		// ZHTRecordResource($filePath, (int)$fromType, 2);

		$savePath = ltrim($savePath,'/');
		$info = null;
		$rdata = ['status'=>1,'savePath'=>$savePath,'name'=>$imgSrc];
    return json_encode($rdata);
	}else{
		//上传失败获取错误信息
		return $file->getError();
	}
}
/**
 * 生成验证码
 */
function ZHTVerify(){
	$Verify = new \verify\Verify();
  $Verify->length = 4;
  $Verify->entry();
}
/**
 * 核对验证码
 */
function ZHTVerifyCheck($code){
	$code = str_replace(' ','',$code);
	$verify = new \verify\Verify();
	return $verify->check($code);
}
/**
 * 生成默认商品编号/货号
 */
function ZHTGoodsNo($pref = ''){
	return $pref.(round(microtime(true),4)*10000).mt_rand(0,9);
}
/**
 * 获取订单统一流水号
 */
function ZHTOrderQnique(){
	return (round(microtime(true),4)*10000).mt_rand(1000,9999);
}
/**
 * 生成订单号
 */
function ZHTOrderNo(){
	$orderId = Db::name('orderids')->insertGetId(['rnd'=>time()]);
	return $orderId.(fmod($orderId,7));
}
/**
 * 判断有没有权限
 * @param $code 权限代码
 * @param $type 返回的类型  true-boolean   false-string
 */
function ZHTGrant($code){
	$STAFF = session("ZHT_STAFF");
	// dump($STAFF);
	if(in_array($code,$STAFF['privilege']))return true;
	return false;
}
/**
 * 加载系统访问路径
 */
function ZHTVisitPrivilege(){
	$listenUrl = cache('ZHT_LISTEN_URL');
	if (!$listenUrl) {
		$list = model('admin/Privilege')->getAllPrivilege();
		$listenUrl = [];
		foreach ($list as $v) {
			$v['privilegeUrl'] = trim($v['privilegeUrl']);
			if ($v['privilegeUrl'] == '') continue;
			$listenUrl[strtolower($v['privilegeUrl'])][$v['privilegeCode']] = [
				'code' => $v['privilegeCode'],
				'url' => strtolower($v['privilegeUrl']),
				'name' => $v['privilegeTitle'],
				'isParent' => true,
				'menuId' => $v['menuId']
			];
			if (strpos($v['otherPrivilegeUrl'], '/') !== false) {
				$t = explode(',', $v['otherPrivilegeUrl']);
				foreach ($t as $vv) {
					$vv = trim($vv);
					if (strpos($vv, '/') !== false) {
						$listenUrl[strtolower($vv)][$v['privilegeCode']] = [
							'code' => $v['privilegeCode'],
							'url' => strtolower($vv),
							'name' => $v['privilegeTitle'],
							'isParent' => false,
							'menuId' => $v['menuId']
						];
					}
				}
			}
		}
		cache('ZHT_LISTEN_URL', $listenUrl);
	}
	return $listenUrl;
}
/**
 * 获取用户等级
 */
function ZHTUserRank($userScore){
	$data = cache('ZHT_USER_RANK');
	if(!$data){
		$data =  Db::name('user_rank')->where('dataFlag',1)->order('startScore asc,rankId desc')->select();
	  cache('ZHT_USER_RANK',$data,2592000);
	}
	if(!$data)$data = [];
	foreach ($data as $key => $v) {
		if($userScore>=$v['startScore'] && $userScore<$v['endScore'])return $v;
	}
	return ['rankTitle'=>'','rankId'=>0,'rankImg'=>''];
}
/**
 * 获取上传目录图片尺寸
 */
function ZHTImgSize($dataVal){
	$data = cache('ZHT_IMG_SIZE');
	if(!$data){
		$rs =  Db::name('data')->where([['catId','=',1],['dataFlag','=',1]])->select();
		foreach ($rs as $key => $v){
			$data[$v['dataVal']] = $v['dataDesc'];
		}
	  cache('ZHT_IMG_SIZE',$data,2592000);
	}
	return $data[$dataVal];
}
/**
 * 获取业务数据内容【根据catId获取】
 */
function ZHTData($catId,$id = -99){
	$data = cache('ZHT_DATA');
	if(!$data){
		$rs = Db::name('data')->where(['dataFlag'=>1])->order('catId asc,dataSort asc,dataId asc')->select();
		$data = [];
		foreach ($rs as $key =>$v){
			$data[$v['catId']][$v['dataVal']] = $v;
		}
		cache('ZHT_DATA',$data,378432000);
	}
	if(isset($data[$catId])){
		if($id==-99)return $data[$catId];
		return isset($data[$catId][$id])?$data[$catId][$id]:'';
	}
	return [];
}
/**
 * 获取areaId,areaIdPath获取areaName
 * $num=0省1市2县 -1直接按$areaId处理
 */
function ZHTArea($areaIdPath,$num=2){
	if($areaIdPath=='')return '';
	$data = cache('ZHT_AREA');
	if(!$data){
		$rs = Db::name('area')->where(['dataFlag'=>1])->field('areaId,areaName')->order('areaId asc')->select();
		$data = [];
		foreach ($rs as $key =>$v){
			$data[$v['areaId']] = $v['areaName'];
		}
		cache('ZHT_AREA',$data,378432000);
	}
	if($num == -1){
		return $data[$areaIdPath];
	}else{
		if($areaIdPath != ''){
			$tmp = explode('_', $areaIdPath);
			return $data[$tmp[$num]];
		}
	}
	return '';
}
/**
 * 根据areaId获取areaIdPath
 */
function ZHTGetAreaIdPath($areaId){
	$areaIds = ZHTGetAreaIdPath_($areaId);
	if(!empty($areaIds))$areaIdPath = implode('_',$areaIds)."_";
	return $areaIdPath;
}
/**
 * 根据子分类获取其父级分类
 */
function ZHTGetAreaIdPath_($id,$data = array()){
	$data[] = $id;
	$parentId = Db::name('area')->where('areaId',$id)->value('parentId');
	if($parentId==0){
		krsort($data);
		return $data;
	}else{
		return ZHTGetAreaIdPath_($parentId, $data);
	}
}
/**
 * 获取所有省市县，拆分成3级
 */
function ZHTAreaList(){
	$data = cache('ZHT_AREA_LIST');
	if(!$data){
		$rs = Db::name('area')->where(['dataFlag'=>1])->field('parentId,areaId,areaName')->order('areaId asc')->select();
		$data = ZHTAreaList_($rs, 0);
		cache('ZHT_AREA_LIST',$data,378432000);
	}
	return $data;
}
/**
 * 组装成3级
 */
function ZHTAreaList_($data,$parentId){
	$tree = [];
	foreach($data as $k=>$v){
		if($v['parentId']==$parentId){
			// 再找其下级分类
			$v['children'] = ZHTAreaList_($data,$v['areaId']);
			$tree[] = $v;
		}
	}
	return $tree;
}
/**
 * 资金来源-以后改为ZHTData
 */
function ZHTLangMoneySrc($v){
	switch($v){
		case 1:return '商品订单';
		case 2:return '订单结算';
		case 3:return '提现申请';
		case 4:return '钱包充值';
		case 5:return '商家入驻缴纳年费';
		case 6:return '供货商入驻缴纳年费';
		case 10001:return '管理员';
		default:return '其他';
	}
}
/**
 * 支付来源
 */
function ZHTLangPayFrom($pkey = '',$type = 0){
	$paySrc = cache('ZHT_PAY_SRC');
	if(!$paySrc){
		$paySrc = Db::name('payment')->order('dataSort desc')->select();
		cache('ZHT_PAY_SRC',$paySrc,31622400);
	}
	if($pkey=='' && $type == 1)return $paySrc;
	foreach($paySrc as $v){
		if($pkey==$v['paymentCode'])return $v['paymentTitle'];
	}
	return '其他';
}
/**
 * 将空内容设置为特定内容
 * @param string $v 要处理的字符串
 * @param string $defaultValue 若被处理的字符串的符合函数内的条件，则该值返回
 */
function ZHTBlank($v,$defaultValue = ''){
	if($v=='')return $defaultValue;
	if($v=='0000-00-00')return $defaultValue;
	if($v=='0000-00-00 00:00:00')return $defaultValue;
	return $v;
}
/**
 * 获取商城搜索关键字
 */
function ZHTHotSearch(){
	$keys = ZHTConf("CONF.hotSearch");
	if($keys!='')$keys = explode(',',$keys);
	return $keys;
}
/**
 * 获取文库搜索关键字
 */
function ZHTWordHotSearch(){
	$keys = ZHTConf("CONF.wordHotSearch");
	if($keys!='')$keys = explode(',',$keys);
	return $keys;
}
/**
 * 检测登录账号是否可用
 * @param $key 要检测的内容
 */
function ZHTCheckLoginKey($val,$userId = 0){
    if($val=='')return ZHTReturn("账号不能为空");
    // if(!ZHTCheckFilterWords($val,ZHTConf("CONF.registerLimitWords"))){
    // 	return ZHTReturn("登录账号包含非法字符");
    // }
    $dbo = Db::name('user')->where([["userAccount|userEmail|userTel",'=',$val],['dataFlag','=',1]]);
    if($userId>0){
    	$dbo->where("userId", "<>", $userId);
    }
    $rs = $dbo->count();
    if($rs==0){
    	return ZHTReturn("账号可用",1);
    }
    return ZHTReturn("账号已存在");
}
/**
 * 邮件发送函数
 * @param string to      要发送的邮箱地址
 * @param string subject 邮件标题
 * @param string content 邮件内容
 * @return array
 */
function ZHTSendMail($to, $subject, $content) {
	$rs = [];
	if(ZHTConf("CONF.mailOpen")==1){
		require Env::get('root_path') . 'extend/phpmailer-master/PHPMailerAutoload.php';
		require_once(Env::get('root_path') . 'extend/phpmailer-master/class.phpmailer.php');
		require_once(Env::get('root_path') . 'extend/phpmailer-master/class.smtp.php');
		$mail = new PHPMailer();
		$mail->CharSet="UTF-8";           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置为 UTF-8
		$mail->IsSMTP();                  //设定使用SMTP服务
		$mail->SMTPAuth = true;           //启用SMTP验证功能
		$mail->SMTPSecure = "ssl";        //启用SSL
		$mail->SMTPDebug = 0;
		$mail->Host = ZHTConf("CONF.mailSmtp");     //SMTP服务器
		$mail->Port = 465;                //SMTP服务器的端口号
		$mail->Username = ZHTConf("CONF.mailUserName");  //SMTP服务器用户名
		$mail->Password = ZHTConf("CONF.mailPassword");  //SMTP服务器密码
		$mail->SetFrom(ZHTConf("CONF.mailAddress"), ZHTConf("CONF.mailUserName"));   //设置发件人地址和名称
		// $mail->AddReplyTo("b***@example.com","b***");  //设置邮件回复人地址和名称
		$mail->Subject = $subject;  //设置邮件标题
		// $mail->AltBody = "为了查看该邮件，请切换到支持HTML的邮件客户端"; //可选项，向下兼容考虑
		$mail->MsgHTML($content); //设置邮件内容
		$mail->AddAddress($to, "");
		// $mail->AddAttachment("images/phpmailer.gif");                    //附件
		
		// 发送邮件
		$rs =array();
		if (!$mail->Send()) {
			$rs['status'] = 0;
			$rs['msg'] = $mail->ErrorInfo;
				return $rs;
		} else {
			$rs['status'] = 1;
				return $rs;
		}
	}
	return ['status'=>0,'msg'=>'未开启邮件发送功能'];
}
/**
 * 邮件发送函数-端口25阿里云不开放，不能用
 * @param string to      要发送的邮箱地址
 * @param string subject 邮件标题
 * @param string content 邮件内容
 * @return array
 */
function ZHTSendMail2($to, $subject, $content) {
	$rs = [];
	if(ZHTConf("CONF.mailOpen")==1){
		require Env::get('root_path') . 'extend/phpmailer/phpmailer.php';
		$mail = new \phpmailer\phpmailer();
	    // 装配邮件服务器
	    $mail->IsSMTP();
	    $mail->SMTPDebug = 0;
	    $mail->Timeout = 5;
	    $mail->Host = (ZHTConf("CONF.mailOpenSSL")==1?'ssl://':'').ZHTConf("CONF.mailSmtp");
	    $mail->SMTPAuth = ZHTConf("CONF.mailAuth");
	    $mail->Username = ZHTConf("CONF.mailUserName");
	    $mail->Password = ZHTConf("CONF.mailPassword");
	    $mail->CharSet = 'utf-8';
	    $mail->Port = ZHTConf("CONF.mailPort");
	    // 装配邮件头信息
	    $mail->From = ZHTConf("CONF.mailAddress");
	    $mail->AddAddress($to);
	    $mail->FromName = ZHTConf("CONF.mailSendTitle");
	    $mail->IsHTML(true);
	    // 装配邮件正文信息
	    $mail->Subject = $subject;
	    $mail->Body = $content;
	    // 发送邮件
	    $rs =array();
	    if (!$mail->Send()) {
	    	$rs['status'] = 0;
	    	$rs['msg'] = $mail->ErrorInfo;
	        return $rs;
	    } else {
	    	$rs['status'] = 1;
	        return $rs;
	    }
	}
	return ['status'=>0,'msg'=>'未开启邮件发送功能'];
}
/**
 * 字符串替换
 * @param string $str     要替换的字符串
 * @param string $repStr  即将被替换的字符串
 * @param int $start      要替换的起始位置,从0开始
 * @param string $splilt  遇到这个指定的字符串就停止替换
 */
function ZHTStrReplace($str,$repStr,$start,$splilt = ''){
	$newStr = substr(utf8_encode($str),0,$start);
	$breakNum = -1;
	for ($i=$start;$i<strlen($str);$i++){
		$char = substr($str,$i,1);
		if($char==$splilt){
			$breakNum = $i;
			break;
		}
		$newStr.=$repStr;
	}
	if($splilt!='' && $breakNum>-1){
		for ($i=$breakNum;$i<strlen($str);$i++){
			$char = substr($str,$i,1);
			$newStr.=$char;
		}
	}
	return $newStr;
}
/**
 * 获取消息模板
 */
function ZHTMsgTemplates($tplCode){
	$data = cache('ZHT_MSG_TEMPLATES');
	if(!$data){
		$rs = Db::name('tpl_message')->order('tplId asc')->select();
		$data = [];
		foreach ($rs as $key =>$v){ // 邮件模板$tplType=2有编辑器，模板内容不用清除html代码，其他模板（消息模板，短信模板）以后用到再说
			// if($v['tplContent']==''){
				$data[$v['tplCode']] = $v;
			// }else{
			// 	$v['content'] = htmlspecialchars_decode($v['tplContent']);
			// 	$v['tplContent'] = strip_tags(htmlspecialchars_decode($v['tplContent']));
			// 	$data[$v['tplCode']] = $v;
			// }
		}
		cache('ZHT_MSG_TEMPLATES',$data,378432000);
	}
	return (isset($data[$tplCode]))?$data[$tplCode]:null;
}
/**
 * 截取字符串
 */
function ZHTSubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = false){
	$newStr = '';
	if (function_exists ( "mb_substr" )) {
		$newStr = mb_substr ( $str, $start, $length, $charset );
		if ($suffix && (mb_strlen($str,$charset)>$length))$newStr .= "...";
	} elseif (function_exists ( 'iconv_substr' )) {
		$newStr = iconv_substr( $str, $start, $length, $charset );
		if ($suffix && (mb_strlen($str,$charset)>$length))$newStr .= "...";
	}
	if($newStr==''){
	$re ['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
	$re ['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
	$re ['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
	$re ['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
	preg_match_all ( $re [$charset], $str, $match );
	$slice = join ( "", array_slice ( $match [0], $start, $length ) );
	if ($suffix)
		$newStr = $slice;
	}
	return $newStr;
}
/**
 * 中英混合的字符串截取
 */
function ZHTCutstr($sourcestr,$cutlength) {
	$returnstr = '';
	$i = 0;
	$n = 0;
	$str_length = strlen ($sourcestr); //字符串的字节数
	while ( ($n < $cutlength) and ($i <= $str_length) ) {
		$temp_str = substr ($sourcestr, $i, 1 );
		$ascnum = Ord ( $temp_str ); //得到字符串中第$i位字符的ascii码
		if ($ascnum >= 224) //如果ASCII位高与224，
		{
			$returnstr = $returnstr . substr ($sourcestr, $i, 3 ); //根据UTF-8编码规范，将3个连续的字符计为单个字符  
			$i = $i + 3; //实际Byte计为3
			$n ++; //字串长度计1
		} elseif ($ascnum >= 192) //如果ASCII位高与192，
		{
			$returnstr = $returnstr . substr ($sourcestr, $i, 2 ); //根据UTF-8编码规范，将2个连续的字符计为单个字符
			$i = $i + 2; //实际Byte计为2
			$n ++; //字串长度计1
		} elseif ($ascnum >= 65 && $ascnum <= 90) //如果是大写字母，
		{
			$returnstr = $returnstr . substr ($sourcestr, $i, 1 );
			$i = $i + 1; //实际的Byte数仍计1个
			$n ++; //但考虑整体美观，大写字母计成一个高位字符
		} else //其他情况下，包括小写字母和半角标点符号，
		{
			$returnstr = $returnstr . substr ($sourcestr, $i, 1 );
			$i = $i + 1; //实际的Byte数计1个
			$n = $n + 0.5; //小写字母和半角标点等与半个高位字符宽...
		}
	}
	// 防止返回字符串出现：222千克&nbsp;&nb  这种情况
	if(substr($returnstr,strrpos($returnstr,'&')+5,1)!=';' && strrpos($returnstr,'&')){
			$returnstr=substr_replace($returnstr,'',strrpos($returnstr,'&'),strlen($returnstr)-strrpos($returnstr,'&'));
	}
	if ($str_length > $cutlength) {
		$returnstr = $returnstr . "..."; //超过长度时在尾处加上省略号
	}
	return $returnstr;
}
/**
 * 将字符串转换为时间戳，解决部分服务器时间不能超过2038的问题
 */
function ZHTStrToTime($str){
	if(strtotime('2099-09-09 23:59:59')){
			return strtotime($str);
	}else{
			 $date = new DateTime($str);
			return $date->format('U');
	}
}
/**
* 计算剩余时间
*/
function ZHTTimeToStr($second){
 $day = floor($second/(3600*24));
 $second = $second%(3600*24);//除去整天之后剩余的时间
 $hour = floor($second/3600);
 $second = $second%3600;//除去整小时之后剩余的时间
 $minute = floor($second/60);
 $second = $second%60;//除去整分钟之后剩余的时间
 //返回字符串
 return (($day>0)?($day.'天'):"").($hour<10?"0".$hour:$hour).':'.($minute<10?"0".$minute:$minute).':'.($second<10?"0".$second:$second);
}
/**
 * 比较两个日期相差的天数
 * $date1 开始日期  Y-m-d
 * $date2 结束日期  Y-m-d
 */
function ZHTCompareDate($date1,$date2){
	// $time1 = strtotime($date1);
	// $time2 = strtotime($date2);
	// echo $date1;
	// echo '<br>';
	// echo $date2;
	// echo '<br>';
	// echo ceil(($date1-$date2)/86400);
	return ceil(($date1-$date2)/86400);
}
/**
 * 格式化日期
 */
function ZHTDay($str){
	if($str != ''){
		$str = date('Y-m-d',$str);
	}
	return $str;
}
/**
 * 提供原生分页处理
 */
function ZHTPager($total,$rs,$page,$size = 0){
	$pageSize = ($size>0)?$size:config('paginate.list_rows');
	$totalPage = ($total%$pageSize==0)?($total/$pageSize):(intval($total/$pageSize)+1);
	return ['total'=>$total,'per_page'=>$pageSize,'current_page'=>$page,'last_page'=>$totalPage,'data'=>$rs];
}
/**
 * 根据指定的商品分类获取其路径
 */
function ZHTPathGoodsCat($catId,$data = array()){
	$rs = Db::table('__GOODS_CAT__')->where(['isShow'=>1,'dataFlag'=>1,'catId'=>$catId])->field("parentId,catTitle,catId,catType")->find();
	$data[] = $rs;
	if($rs['parentId']==0){;
		krsort($data);
		return $data;
	}else{
		return ZHTPathGoodsCat($rs['parentId'],$data);
	}
}
/**
 * 获取指定商品分类的子分类列表/获取指定的商品分类，靠$isSelf=-1判断
 */
function ZHTGoodsCats($parentId = 0,$catType = -1,$isFloor = -1,$isSelf = 0){
	if($isSelf==1){
    return Db::name('goods_cat')->where(['dataFlag'=>1, 'isShow' => 1,'catId'=>$parentId])
                 ->field("catTitle,simpleTitle,catId,parentId")->order('dataSort asc')->find();
	}else{
		$dbo = Db::name('goods_cat')->where(['dataFlag'=>1, 'isShow' => 1,'parentId'=>$parentId]);
	  if($catType!=-1 and $parentId==0)$dbo->where('catType',$catType);
	  if($isFloor!=-1)$dbo->where('isFloor',$isFloor);
	  return $dbo->field("catTitle,simpleTitle,catId")->order('catType asc,dataSort desc,catId asc')->select();
	}
}
/**
 * 根据子分类循环获取其父级分类
 */
function ZHTGoodsCatPath($catId, $data = []){
	if($catId==0)return $data;
	$data[] = $catId;
	$parentId = Db::name('goods_cat')->where('catId',$catId)->value('parentId');
	if($parentId==0){
		krsort($data);
		return $data;
	}else{
		return ZHTGoodsCatPath($parentId, $data);
	}
}
/**
 * 获取指定行业的子分类列表/获取指定的行业
 */
function ZHTTrade($parentId = 0){
	$rs = Db::name('trade')
		->where(['dataFlag'=>1, 'isShow' => 1,'parentId'=>$parentId])
		->field("tradeTitle,tradeId,tradeFee")
		->order('dataSort desc,tradeId asc')
		->select();
	return $rs;
}
/**
 * 高精度数字相加
 * @param $num
 * @param number $i 保留小数位
 */
function ZHTBCMoney($num1,$num2,$i=2){
	$num = bcadd($num1, $num2, $i);
	return $num;
	// return (float)$num;
}
/**
 * 将传过来的字符串格式化为数值字符串
 * @param string $split 要格式的字符串
 * @param string $str 字符串中的分隔符号
 * @param boolean $isJoin 是否连成字符串返回
 */
function ZHTFormatIn($split,$str,$isJoin = true){
	if($str=='')return $isJoin?'':[];
	$strdatas = explode($split,$str);
	$data = array();
	for($i=0;$i<count($strdatas);$i++){
		$data[] = (int)$strdatas[$i];
	}
	$data = array_unique($data);
	if($isJoin)return implode($split,$data);
	return $data;
}
/**
 * 用户下单可用积分
 * isUseScore  -1:仅仅计算最大可用积分   0：不使用积分   1：使用积分
 */
function ZHTOrderUsableScore($goodsTotalMoney,$userId = 0,$isUseScore = -1,$useScore = 0){
	//如果没开启积分支付则返回为0
	$isOpenScorePay = (int)ZHTConf('CONF.isOpenScorePay');
	if($isOpenScorePay==0)return ['score'=>0,'money'=>0];
	//不使用积分则返回0
	if($isUseScore==0)return ['score'=>0,'money'=>0];
	//开始计算最大可用积分
	$userId = ($userId>0)?$userId:(int)session('ZHT_USER.userId');
	$user = model('common/user')->getFieldsById($userId,'userScore');
	$orderUsableScoreRate = (int)ZHTConf('CONF.orderUsableScoreRate');
	$goodsTotalMoney = $goodsTotalMoney*$orderUsableScoreRate/100;
	//计算可抵金额对应的积分
	$goodsTotalScore = ZHTScoreToMoney($goodsTotalMoney,true);
	//校验积分是否和金额对应，可能一开始的金额计算出来的积分并没有对应（因为四舍五入了）
	$goodsTotalMoney2 = ZHTScoreToMoney($goodsTotalScore);
	$goodsTotalMoney = ($goodsTotalMoney>$goodsTotalMoney2)?$goodsTotalMoney2:$goodsTotalMoney;
	if($goodsTotalScore==0)return ['score'=>0,'money'=>0];
	$useOrderScore =0;
	$useOrderMoney = 0;
	//可抵积分不能大于用户的可用积分
	if($user['userScore']>$goodsTotalScore){
			$useOrderScore = $goodsTotalScore;
			$useOrderMoney = $goodsTotalMoney;
	}else{
			$useOrderScore = $user['userScore'];
			$useOrderMoney = ZHTScoreToMoney($useOrderScore);
	}
	if($isUseScore!=-1){
			//如果传进来的使用积分为负数则置0
			$useScore = ($useScore<=0)?0:$useScore;
			//如果用户要使用的积分小于可抵积分，则将可抵积分调小,并重新计算可抵金额
			if($isUseScore==1 ){
					if($useOrderScore>$useScore){
							$useOrderScore = $useScore;
							$useOrderMoney = ZHTScoreToMoney($useOrderScore);
					}
			}
	}
	return ['score'=>$useOrderScore,'money'=>$useOrderMoney];
}
/**
 * 金额兑积分
 */
function ZHTMoneyGiftScore($money){
	$moneyToScore = (float)ZHTConf('CONF.moneyToScore');
	return intval($money*$moneyToScore);
}
/**
* 积分兑金额
* $isBack=true则$score实际上传入金额，通过金额反推需要兑换的积分
*/
function ZHTScoreToMoney($score,$isBack = false){
	$scoreToMoney = (int)ZHTConf('CONF.scoreToMoney');
	if($scoreToMoney<=0)return 0;
	if($isBack){
			return intval(strval($score*$scoreToMoney));
	}else{
		return round($score/$scoreToMoney,2);
	}
}
/**
 * 保持数值为大于0的数值
 */
function ZHTPositiveNum($num){
	// return ($num>0)?round($num,2):0;
	return ($num>0)?sprintf("%.2f", round($num,2)):0;
}
/**
 * 根据送货城市获取运费
 * @param $cityId 送货城市Id
 * @param $shopId 店铺ID
 * @param $carts 购物车信息
 */
function ZHTOrderFreight($shopId,$cityId,$carts=[]){
	$cnt = Db::name("shop_express")->where(["shopId"=>$shopId,"dataFlag"=>1,"isEnable"=>1])->count();
	$freight = 0;
	if($cnt>0){
		$freight = model("home/cart")->getShopFreight($shopId,$cityId,$carts);
	}
	return ($freight>0)?$freight:0;
}
/**
 * URL 64位加密处理
 * @param string $data 字符串内容
 * @param boolean $isEncode true:编码  false:解码
 */
function ZHTBase64url($data,$isEncode = true) {
  return ($isEncode)?rtrim(strtr(base64_encode($data), '+/', '-_'), '='):base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}
/**
 * URL 64位加密处理[编码]
 * @param string $data 字符串内容
 */
function ZHTBase64urlEncode($data){
	$secretKey = ZHTConf('CONF.urlSecretKey');
	$base64 = new \org\Base64();
 	$key = ZHTBase64url($base64->encrypt($data, $secretKey),true);
 	return $key;
}

/**
 * URL 64位加密处理[解码]
 * @param string $data 字符串内容
 */
function ZHTBase64urlDecode($data){
	$secretKey = ZHTConf('CONF.urlSecretKey');
	$key = ZHTBase64url($data,false);
	$base64 = new \org\Base64();
	$key = $base64->decrypt($key,$secretKey);
	return $key;
}
/**
 * 获取订单核验码
 * type 0：商家订单 1：供货商订单
 */
function ZHTOrderVerificationCode($id,$type=0){
	$time= microtime();
	$arr=explode(" ",$time);
	$micro=$arr[0]*1000000000;
	$micro_str=substr($micro."",0,8);
	$vCode = rand(0,9).($id+$micro_str).rand(100,1000);
	$cnt = 0;
	if($type==1){
			$cnt = Db::name("supplier_orders")->where(["supplierId"=>$id,"deliverType"=>1,"verificationCode"=>$vCode])->count();
	}else{
			$cnt = Db::name("order")->where(["shopId"=>$id,"deliverType"=>1,"verificationCode"=>$vCode])->count();
	}
	if($cnt>0){
			$vCode = ZHTOrderVerificationCode($id,$type);
	}
	return $vCode;
}
/**
 * 获取分类的佣金
 */
function ZHTGoodsCommissionRate($catId){
	$cats = Db::name('goods_cat')->where('catId',$catId)->field('parentId,commissionRate')->find();
	if(empty($cats)){
		return 0;
	}else{
		if((float)$cats['commissionRate']>=0)return (float)$cats['commissionRate'];
		return ZHTGoodsCommissionRate($cats['parentId']);
	}
}
/**
 * 获取首页左侧分类、推荐品牌和广告
 */
function ZHTSideCategorys($catType = 0){
	$data = cache('ZHT_SIDE_CATS_'.$catType);
	if(!$data){
			$cats1 = Db::table('__GOODS_CAT__')->where([['dataFlag','=',1], ['isShow','=',1],['parentId','=',0],['catType','=',$catType]])->field("catTitle,catId,catImg")->order('catType asc,dataSort desc')->select();
			if(count($cats1)>0){
					$ids1 = [];$ids2 = [];$cats2 = [];$cats3 = [];$mcats3 = [];$mcats2 = [];
					foreach ($cats1 as $key =>$v){
							$ids1[] = $v['catId'];
					}
					$tmp2 = Db::table('__GOODS_CAT__')->where([['dataFlag','=',1], ['isShow','=',1],['parentId','in',$ids1]])->field("catTitle,catId,parentId,catImg")->order('dataSort desc')->select();
					if(count($tmp2)>0){
							foreach ($tmp2 as $key =>$v){
									$ids2[] = $v['catId'];
							}
							$tmp3 = Db::table('__GOODS_CAT__')->where([['dataFlag','=',1], ['isShow','=',1],['parentId','in',$ids2]])->field("catTitle,catId,parentId,catImg")->order('dataSort desc')->select();
							if(count($tmp3)>0){
									//组装第三级
									foreach ($tmp3 as $key =>$v){
											$mcats3[$v['parentId']][] = $v;
									}
							}
							//组装第二级
							foreach ($tmp2 as $key =>$v){
									if(isset($mcats3[$v['catId']]))$v['list'] = $mcats3[$v['catId']];
									$mcats2[$v['parentId']][] = $v;
							}
							//组装第一级
							foreach ($cats1 as $key =>$v){
									if(isset($mcats2[$v['catId']]))$cats1[$key]['list'] = $mcats2[$v['catId']];
							}
					}
					unset($ids1,$ids2,$cats2,$cats3,$mcats3,$mcats2);
			}
			cache('ZHT_SIDE_CATS_'.$catType,$cats1);
			return $cats1;
	}
	return $data;
}
/**
 * 获取前台会员中心菜单
 */
function ZHTHomeMenu(){
	$ms = model('HomeMenu')->getMenus();
	$request = request(); // 获取当前url请求对象
	$urls = ZHTConf('protectedUrl2'); // 前台受保护的菜单 菜单有主菜单和附属url，分别对应menuId
	$visit = strtolower($request->module() . "/" . $request->controller() . "/" . $request->action()); // 获取模型 控制器 方法
	// dump($urls);
	// die;
	if (isset($urls[$visit])) {
		$ms[1]['menuId'] = (int)$urls[$visit];
	}else{
		$ms[1]['menuId'] = 0;
	}
  // 店铺菜单 $ms[1]是买家中心菜单, $ms[2]是卖家中心菜单
	return $ms[1];
}
/**
 * 根据$userId获取会员的技工申请状态userSkill
 */
function ZHTuserSkill($userId){
	$userSkill = Db::name('user')->where('userId',$userId)->value('userSkill');
	return $userSkill;
}
/**
* 发送商城消息
* @param int 	$to 接受者d
* @param string $content 内容
* @param array  $msgJson 存放json数据
*/
function ZHTSendMsg($to,$content,$msgJson=[],$msgType = 1){
	$message = [];
	$message['msgType'] = $msgType;
	$message['sendUserId'] = 1;
	$message['create_time'] = time();
	$message['msgStatus'] = 0;
	$message['dataFlag'] = 1;

	$message['receiveUserId'] = $to;
	$message['msgContent'] = $content;
	$message['msgJson'] = json_encode($msgJson);
	// 推送消息
	// hook('pushNoticeToApp', ["type"=>"pushToSingle", "userId"=>$to, "title"=>"新消息", "content"=>$content]);
	Db::name('message')->insert($message);

}
/**
 * 获取指定的记录
 */
function ZHTTable($table,$where = [],$field = '*',$num = 1,$order = ''){
	$db = Db::name($table);
	if(!empty($where))$db->where($where);
	if($field!='*')$db->field($field);
	if($num>1){
			if($order!='')$db->order($order);
			return $db->select();
	}else{
			return $db->find();
	}
}
/**
 * @todo 敏感词过滤，返回结果
 * @param array $list  定义敏感词一维数组
 * @param string $string 要过滤的内容
 * @return string $log 处理结果
 */
function ZHTSensitive($string){
	$list = ZHTConf('CONF.sensitiveWord');
  $count = 0; //违规词的个数
  $sensitiveWord = '';  //违规词
  $stringAfter = $string;  //替换后的内容
  // $pattern = "/".implode("|",$list)."/i"; //定义正则表达式,过滤词$list为数组
  $pattern = "/".$list."/i"; //定义正则表达式,过滤词$list为以|分隔的字符串
  if(preg_match_all($pattern, $string, $matches)){ //匹配到了结果
    $patternList = $matches[0];  //匹配到的数组
    $count = count($patternList);
    $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
    $replaceArray = array_combine($patternList,array_fill(0,count($patternList),'*')); //把匹配到的数组进行合并，替换使用
    $stringAfter = strtr($string, $replaceArray); //结果替换
  }
  // $log = "原句为 [ {$string} ]<br/>";
  if($count==0){
    // $log .= "暂未匹配到敏感词！";
		return $string;
  }else{
    // $log .= "匹配到 [ {$count} ]个敏感词：[ {$sensitiveWord} ]<br/>".
    //   "替换后为：[ {$stringAfter} ]";
		return $stringAfter;
  }  
}
/**
 * 获取周几
 */
function ZHTgetWeek($date){
	$today = date('Y-m-d');
	$tomorrow = date('Y-m-d',strtotime("+1 day"));
	$afterTomorrow = date('Y-m-d',strtotime("+2 day"));
	//强制转换日期格式
	$number_wk=date("w",strtotime($date));
	$weekArr=array("周日","周一","周二","周三","周四","周五","周六");
	if($date == $today){
		return '今天';
	}elseif($date == $tomorrow){
		return '明天';
	}elseif($date == $afterTomorrow){
		return '后天';
	}else{
		return $weekArr[$number_wk];
	}	
}
/**
 * 未来30天日期列表
 */
function ZHT30Days(){
  $days=[];
  for ($i=0; $i <=30; $i++) {
    $days[$i]=date("Y-m-d",strtotime($i.'day'));
  }
  return $days;
}
/**
 * 判断是否是微信浏览器
 */
function ZHTIsWeixin() { 
	if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) { 
			return true; 
	} return false; 
}
/**
 * 生成唯一标志*标准的UUID
 */
function ZHTUuid()  {  
  $chars = md5(uniqid(mt_rand(), true));
  return $chars ;  
} 
/**
 * 以get方式提交请求
 * @param $url
 * @return bool|mixed
 */
function ZHTHttpGet($url){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_SSLVERSION, 1);
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_TIMEOUT, 30);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	list($content, $status) = array(curl_exec($curl), curl_getinfo($curl), curl_close($curl));
	return (intval($status["http_code"]) === 200) ? $content : false;
}
/**
* 以post方式提交请求
* @param string $url
* @param array|string $data
* @return bool|mixed
*/
function ZHTHttpPost($url, $data){
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	// curl_setopt($curl, CURLOPT_POSTFIELDS, _buildPost($data)); // 不知道什么用，先不用了
	list($content, $status) = array(curl_exec($curl), curl_getinfo($curl), curl_close($curl));
	return (intval($status["http_code"]) === 200) ? $content : false;
}
/**
* 使用证书，以post方式提交xml到对应的接口url
* @param string $url POST提交的内容
* @param array $data 请求的地址
* @param string $ssl_cer 证书Cer路径 | 证书内容
* @param string $ssl_key 证书Key路径 | 证书内容
* @param int $second 设置请求超时时间
* @return bool|mixed
*/
function ZHTHttpsPost($url, $data, $ssl_cer = null, $ssl_key = null, $second = 30)
{
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_TIMEOUT, $second);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	if (!is_null($ssl_cer) && file_exists($ssl_cer) && is_file($ssl_cer)) {
			curl_setopt($curl, CURLOPT_SSLCERTTYPE, 'PEM');
			curl_setopt($curl, CURLOPT_SSLCERT, $ssl_cer);
	}
	if (!is_null($ssl_key) && file_exists($ssl_key) && is_file($ssl_key)) {
			curl_setopt($curl, CURLOPT_SSLKEYTYPE, 'PEM');
			curl_setopt($curl, CURLOPT_SSLKEY, $ssl_key);
	}
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
	// curl_setopt($curl, CURLOPT_POSTFIELDS, _buildPost($data)); // 不知道什么用，先不用了
	list($content, $status) = array(curl_exec($curl), curl_getinfo($curl), curl_close($curl));
	return (intval($status["http_code"]) === 200) ? $content : false;
}

/**
* POST数据过滤处理
* @param array $data
* @return array
*/
function _buildPost(&$data)
{
	if (is_array($data)) {
			foreach ($data as &$value) {
					if (is_string($value) && $value[0] === '@' && class_exists('CURLFile', false)) {
							$filename = realpath(trim($value, '@'));
							file_exists($filename) && $value = new CURLFile($filename);
					}
			}
	}
	return $data;
}
/*
 *  返回数组中指定多列
 * @param  Array  $input       需要取出数组列的多维数组
 * @param  String $column_keys 要取出的列名，逗号分隔，如不传则返回所有列
 * @param  String $index_key   作为返回数组的索引的列
 * @return Array
*/
function ZHTArrayColumns($input, $column_keys = null, $index_key = null){
	$result = array();
	$keys = isset($column_keys) ? explode(',', $column_keys) : array();
	if ($input) {
		foreach ($input as $k => $v) {
			// 指定返回列
			if (!$keys) {
				$keys = array_keys($v);
			}
			$tmp = array();
			foreach ($keys as $key) {
				$tmp[$key] = $v[$key];
			}
			// 指定索引列
			if (isset($index_key)) {
				$result[$v[$index_key]] = $tmp;
			} else {
				$result[] = $tmp;
			}
		}
	}
	return $result;
}
/**
 * 检测字符串不否包含
 * @param $srcWordArr 被检测的字符串数组
 * @param $filterWords 禁用使用的字符串列表
 * @return boolean true-检测到,false-未检测到
 */
function ZHTCheckFilterWordsArr($srcWordArr, $filterWords) {
	$flag = true;
	$filterWords = '運営,サブスク,開発,ノウハウ,打ち合わせ,プラン,取引,コスト,プログラム';
	if ($filterWords != "") {
		$filterWords = strtolower($filterWords);
		$filterWords = str_replace("，", ",", $filterWords);
		$words = explode(",", $filterWords);
		for ($i = 0; $i < count($words); $i++) {
			if ($words[$i] == '') continue;
			foreach ($srcWordArr as $vo) {
				$srcWord = strtolower($vo);
				if (strpos($srcWord, $words[$i]) !== false) {
					$flag = false;
					break 2;
				}
			}
		}
	}
	return $flag;
}